/**
 * 运行 主题less脚本
 * */
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const { promisify } = require('util');
const glob = promisify(require('glob'));
const theme = require('../config/theme');

const root = './';
const customLessUrl = './public/styles/custom.theme.less';

initTheme();

async function initTheme() {
  _initLess(); // 初始化less
  _startLess(); //启动主题less
}

function _initLess() {
  fs.writeFileSync(customLessUrl, '', 'utf-8'); //写入custom.theme.less 文件，有的话覆盖，没有重新生成一份

  Object.keys(theme).forEach((item) => { //将config下面定义的主题色或其他色写入custom.theme.less文件下
    fs.appendFileSync(customLessUrl, `${item}:${theme[item]};\n`, 'utf-8');
  });
}

async function _startLess() {
  const rootPath = path.resolve(root);
  const fileList = await glob('src/**/*.theme.less', { //查找特定的主题样式文件
    cwd: rootPath,
    ignore: ['node_modules/**', 'src/.umi/**', 'src/.umi-production/**'],
  });

  // global.theme.less 在最前面，优先级最低
  const otherList = [];
  const globalFile = fileList.filter((file) => {
    if (file.indexOf('global.theme.less') > -1) {
      return true;
    }
    otherList.push(file);
    return false;
  });

  globalFile.concat(otherList).forEach((filePath) => {
    writeFile(rootPath, filePath); //将读取的特使文件下的样式添加到custom文件里
  });

  console.info(chalk.greenBright('主题文件扫描完成 ✔✔✔')); // eslint-disable-line
}

// 写文件
function writeFile(rootPath, filePath) {
  console.log(rootPath, filePath);
  const bufferContent = fs.readFileSync(path.resolve(rootPath, filePath));
  const content = bufferContent.toString('utf8');
  fs.appendFileSync(customLessUrl, `\n// ${filePath}\n${content}`, 'utf8');
}

module.exports = initTheme;
